package com.acsm.commons.sms;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;

import cn.brilliantfuture.commentry.util.JDBCDataSource;



/**
 * 
 * Title: Cabinet Platform
 * 
 * Author:  LiTian  
 *
 * Date: 2016年3月3日
 * 
 * Description:
 * 
 */
public class SaveSmsInfo implements SMSCallback{
	
	private static Logger logger = Logger.getLogger(SaveSmsInfo.class);

	
	@SuppressWarnings("unchecked")
	public void callback(String phone,String result,String message) {
		
		Map<String, Object> map=new HashMap<String, Object>();
		map=JSONUtils.toHashMap(result);
		
		logger.info(map.get("msg"));
		
		//Sms send result -> {"model":"100764970713^1101190734996","code":"0","success":true}
		boolean returnValue=(Boolean) map.get("success");
		
		if (result!=null) {
			
			Connection conn = null;
			PreparedStatement pstm = null;
			
			try {
				conn = JDBCDataSource.getConnection();
				conn.setAutoCommit(false);
				
				pstm = conn.prepareStatement("insert into send_record(phone, content, sms_channel, status, is_send, insert_time) values (?, ?, ?, ?, ?, now())");
				pstm.setString(1, phone);
				pstm.setString(2, message);
				pstm.setInt(3, 3);
				
				if (true==returnValue) {
					pstm.setInt(4, 7);
					pstm.setBoolean(5, true);
				}else {
					pstm.setInt(4, 8);
					pstm.setBoolean(5, false);
				}
				
				pstm.executeUpdate();
				
				conn.commit();
				conn.setAutoCommit(true);
			} catch (Exception e) {
				try {
					conn.rollback();
				} catch (SQLException e1) {
					logger.error("Rollback fail\n" + e1.getMessage());
				}
				logger.error("Save sms send record fail\n" + e.getMessage());
			} finally {
				try {
					if (pstm != null)
						pstm.close();
					if (conn != null)
						conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
		}
		
	}
	

}
